from flask_restful import Resource, fields, reqparse, abort, marshal

from App.apis.api_constant import USER_ACTION_LOGIN, USER_ACTION_REGISTER, HTTP_CREATE_OK, HTTP_OK, \
    USER_CINEMA_PREFIX
from App.apis.utils import create_prefix_token
from App.ext import cache
from App.models.cinema_admin.cinema_user_model import CinemaUser
from App.models.cinema_admin.model_utils import get_cinema_user

'''
此接口主要用于添加影院用户，用来提交影院相关信息
'''
base_parser = reqparse.RequestParser()  # 实例化配置
base_parser.add_argument("password", required=True, help="plase input password")
base_parser.add_argument("action", required=True)
login_parser = base_parser.copy()
login_parser.add_argument("username", help="Plase  input username")
login_parser.add_argument("phone", help="plase  input  phone")

register_parser = base_parser.copy()

register_parser.add_argument("username", required=True)
register_parser.add_argument("password", required=True)
register_parser.add_argument("phone", help="plase  input  phone")

cinema_user_fields = {
    "username": fields.String,
    "phone": fields.String,
    "password": fields.String(attribute="_password"),
    "is_verify": fields.Boolean,
}

single_cinema_user_fields = {
    "status": fields.Integer,
    "msg": fields.String,
    "data": fields.Nested(cinema_user_fields)
}


class CinemaUsersResource(Resource):
    def post(self):
        args = base_parser.parse_args()
        password = args.get("password")
        if args.get("action") == USER_ACTION_LOGIN.lower():
            login_args = login_parser.parse_args()
            user = get_cinema_user(login_args.get("username")) or get_cinema_user(login_args.get("phone"))
            if not user:
                abort(400, msg="用户不存在")
            if not user.check_password(args.get("password")):
                abort(401, msg="用户密码错误")
            if user.is_delete:
                abort(401, msg="用户未被激活")
            token = create_prefix_token(USER_CINEMA_PREFIX)
            cache.set(token, user.id, timeout=60 * 60 * 7)

            data = {
                "msg": "login  access",
                "status": HTTP_OK,
                "token": token
            }
            return data

        elif args.get("action") == USER_ACTION_REGISTER.lower():
            register_args = register_parser.parse_args()
            moive_user = CinemaUser()
            username = register_args.get("username")
            phone = register_args.get("phone")
            moive_user.username = username
            moive_user.password = password
            moive_user.phone = phone
            if not moive_user.save():
                abort(400, msg="create fail")
            data = {
                "status": HTTP_CREATE_OK,
                "msg": "用户创建成功",
                "data": moive_user,
            }
            return marshal(data, single_cinema_user_fields)

        else:
            abort(400, msg="请提供正确的参数")
